<template>
  <div class="bottom-normal-check vux-1px-t">
    <flexbox :gutter="0" class="">
      <flexboxItem>
        <a id="submit-btn" @click="checkShow=true">查阅</a>
      </flexboxItem>
    </flexbox>
    <div v-transfer-dom>
      <confirm v-model="checkShow" @on-confirm="checkPassSubmit"
              class="turndown-confirm type-text" title="查阅记录" cancel-text="取消" confirm-text="提交查阅">
        <group class="none-bottom-border">
          <cell-box class="cellbox-item">
            <flexbox>
              <flexbox-item class="title" :span="2">
                <p style="padding-top:13px;"></p>
                意见：
              </flexbox-item>
              <flexbox-item class="value" :span="10">
                <x-textarea v-model="checkText" placeholder="请输入意见（必填）" class="txtarea" style="width:auto;"></x-textarea>
              </flexbox-item>
            </flexbox>
          </cell-box>
          <cell-box class="cellbox-item">
            <flexbox>
              <flexbox-item class="title" :span="2">
                附件：
              </flexbox-item>
              <input @change="getFileUrl($event)" type="file" ref="inputDOM" id="upload_file" multiple style="display: none;">
              <flexbox-item class="value" :span="10">
                <div class="annex-inner" v-for="(item,index) in fileList" :key="index">
                  <a :href="item" class="annex-inner-title" target="_blank" >{{item.slice(item.indexOf("_")+1,item.length)}}</a>
                  <div class="annex-inner-close">
                    <i class="icon icon-contract" @click="removeFile(index)"></i>
                  </div>
                </div>
                <i class="icon icon-select" v-if="fileList.length < 9" alt="" @click="fileClick"></i>
                <div class="notes" v-show="fileList.length < 9">可上传jpg/pdf/word格式</div>
              </flexbox-item>
            </flexbox>
          </cell-box>
        </group>
      </confirm>
    </div>
    <!-- 提示彈窗 -->
    <div v-transfer-dom>
      <confirm v-model="requiredShow"
        class="turndown-confirm" title="提示" confirm-text="确认" :show-cancel-button="false" @on-confirm="checkShow=true">
        <p>请输入意见</p>
      </confirm>
    </div>
  </div>
</template>

<script>
  import { Group, CellBox,Flexbox, FlexboxItem, Confirm, XTextarea, TransferDom, Loading } from 'vux';
  import qs from 'qs';
  import { Queue } from '@/assets/js/classLibrary.js';
  let config = {
        //添加请求头
        headers: { "Content-Type": "multipart/form-data" },
        //添加上传进度监听事件
        // onUploadProgress: e => {
        //   var completeProgress = ((e.loaded / e.total * 100) | 0) + "%";
        //   this.progress = completeProgress;
        //   console.log(completeProgress)
        // }
      };
  export default {
    name: 'BottomApproval',
    data () {
      return {
        progress:"",
        fileUploadList:[],
        uploadQueue: new Queue(), // 圖片上傳隊列
        imagesUploadList:[],
        previewerFileList:[],
        fileList:[],
        // 駁回
        checkShow: false,
        checkText: '',
        // 通過
        passShow: false,
        passText: '',
        requiredShow: false
      };
    },
    components: {
      Group,
      CellBox,
      Loading,
      Flexbox,
      FlexboxItem,
      Confirm,
      XTextarea,
    },
    directives: {
      TransferDom
    },
    mounted () {
    },
    methods: {
      getFileUrl: function (e) {
        // input file element
        let inputEl = this.$refs.inputDOM;
        let filesArr = inputEl.files;
        let oldFileLength = this.fileList.length;
        let newFileLength = inputEl.files.length + oldFileLength;
        // 限制文件數量
        if (newFileLength > 9) {
          this.toastShow = true;
          this.toastText = '你只能上传9个文件';
          return false;
        }
        // 遍歷讀取文件
        for (let i = 0; i < filesArr.length; i++) {
          // 限制文件大小
          let size = filesArr[i].size / 1024;
          if (size > 10 * 1024) {
            this.toastShow = true;
            this.toastText = '单个文件大小不能超过10M';
            return false;
          }
          let reader = new FileReader();
          let _this = this;
          reader.onload = function () {
            let result = reader.result;
            let base64Header = result.slice(0, result.indexOf(',') + 1);
            let base64UploadUrl = result.replace(base64Header, '');
            if (!_this.isCorrectfile(base64Header)) {
              alert('只允许上传jpg/pdf/word格式文件');
              return false;
            }
            // _this.fileList.push(filesArr[i])
            _this.fileUploadList.push(filesArr[i]);
            _this.uploadQueue.enqueue(filesArr[i]);
            // 全部加入隊列后執行上傳
            if (i === filesArr.length - 1) {
              _this.uploadFile();
              _this.$parent.loadingShow = true;
              inputEl.value = '';
            }
          };
          reader.readAsDataURL(filesArr[i]);
        }
      },
      // 判断文件是否符合要求
      isCorrectfile: function (url) {
        if (url.indexOf('image') === -1 && url.indexOf('pdf') === -1 && url.indexOf('word') === -1) {
          return false
        };
        return true;
      },
      uploadFile: function () {
        this.$parent.loadingShow = true;
        if (!this.uploadQueue.empty()) {
          let file = this.uploadQueue.getFirst()
          let param = new FormData();
          param.append("name", file.name);
          param.append("file", file);
          this.axios.post('/Process/FileUpdate', param, config)
          .then((res) => {
            this.$parent.loadingShow = false;
            if (res.data.IsScuess === 0) {
              this.fileList.push(...res.data.Filepath)
              this.previewerFileList.push(file.name);
              this.uploadQueue.dequeue();
              this.uploadFile();
            } else {
              this.toastShow = true;
              this.toastText = `上传文件时发生错误，错误信息：${res.data.ExMessage}`;
              this.fileUploadList = [];
              this.uploadQueue.clear();
            }
          })
          .catch((err) => {
            this.$parent.loadingShow = false;
            this.toastShow = true;
            this.toastText = `上传文件时发生错误，错误信息：${err}`;
            this.fileUploadList = [];
            this.uploadQueue.clear();
          });
        } else {
          this.$parent.loadingShow = false;
        }
      },
      removeFile(index){
        this.fileList.splice(index,1)
        this.previewerFileList.splice(index,1)
      },
      fileClick(){
			  document.getElementById('upload_file').click()
		  },
      passClick: function () {
        if (this.passShow) {
          this.passShow = false;
        } else {
          this.passText = '';
          this.passShow = true;
        }
      },
      checkPassSubmit: function () {
        let detailInfo = JSON.parse(this.$route.query.item);
        if (this.isCheckTextNull()) {
          this.requiredShow = true;
          return false;
        }
        let Content = JSON.stringify({
          remarks: this.checkText,
          files:this.fileList
        })
        let postData = {
          data: {
            KeyId: JSON.parse(this.$route.query.item).KeyId,
            StaffNo: this.getUserInfo().StaffNo,
            CreatedStaffNo: detailInfo.CreatedStaffNo,
            Remark: this.passText,
            Content
          }
        };
        this.$parent.loadingShow = true;
        console.log(qs.stringify(postData))
        this.axios.post('/Process/Translate', qs.stringify(postData))
        .then((res) => {
          this.$parent.loadingShow = false;
          if (res.data.IsSuccess) {
            this.$parent.getItemDetail();
            this.$parent.processShow = true;
            this.$parent.bottomWriteCheckShow = false;
            this.$parent.resStatusText = '查阅成功';
            this.$parent.resStatusShow = true;
          } else {
            this.$parent.toastShow = true;
            this.$parent.toastText = `查阅失败，错误信息：${res.data.ExMessage}`;
          }
        })
        .catch((err) => {
          this.$parent.loadingShow = false;
          this.$parent.toastShow = true;
          this.$parent.toastText = `查阅失败，错误信息：${err}`;
        });
      },
      isCheckTextNull: function () {
        if (this.checkText === '') {
          return true;
        }
        return false;
      }
    },
    beforeRouteLeave(to,from,next){
      this.checkShow = false;
      this.$destroy();
      next()
    }
  };
</script>

<style lang="scss" scoped>
  @import '../../assets/style/variable';
  .bottom-normal-check{
    width: 100%;
    position: absolute;
    bottom: 0;
    z-index: 2;
    &:before{
      top: -.5px;
      border-color: #ccc;
    }
    a{
      display: block;
      position: relative;
      font-size: getRem(32);
      line-height: getRem(98);
      background-image: linear-gradient(194deg,
          #fa5864 0%,
          #fc476d 100%),
        linear-gradient(
          #ffffff,
          #ffffff);
      text-align: center;
      color:#fff;
      &.active{
        color: #fff;
        background-image: linear-gradient(194deg,
          #fa5864 0%,
          #fc476d 100%),
        linear-gradient(
          #ffffff,
          #ffffff);
        background-blend-mode: normal,
          normal;
      }
    }
    .vux-1px-l{
      &:before{
        border-color: #ccc;
      }
    }
  }
  .value{
    .annex-inner{
      display:flex;
      justify-content: space-between;
      flex-direction: row;
      align-items: center;
      padding-bottom: 5px;
      .annex-inner-title{
        width:80%;
        white-space:normal;
        overflow: auto;
        font-size: getRem(24);
      }
      .annex-inner-close{
        width:20%;
        text-align: right;
      }
    }
  }
  .notes{
    font-size: getRem(24);
    margin-top: getRem(21.25);
    color: #ccc;
  }
  .icon{
    display: block;
    width: getRem(104.19);
    height: getRem(104.19);
  }
  .icon-contract{
    background: url(../../assets/images/delete_icon@3x.png) no-repeat center;
    background-size: getRem(40) getRem(40);
    height: getRem(60);
  }
  .icon-select{
    background: url(../../assets/images/select-img.png) no-repeat center;
    background-size: getRem(104.19) getRem(104.19);
  }
  .turndown-confirm /deep/ .weui-dialog{
    width:80%;
    max-width: 90%;
  }
  /deep/.vux-flexbox-item.title{
    color: #666!important;
    font-weight: bold;
    font-family: PingFangSC-Regular;
    font-weight: normal;
    font-stretch: normal;
  }
  .turndown-confirm.type-text >>> .weui-dialog__hd{
    padding: 0!important;
    text-align: center!important; 
    color: #fff;
    background-image:-webkit-linear-gradient(256deg, #fa5864 0%, #fc476d 100%),-webkit-linear-gradient(#fff, #fff);
    background-image:linear-gradient(194deg, #fa5864 0%, #fc476d 100%),linear-gradient(#fff, #fff);
  }
  .turndown-confirm /deep/ .weui-dialog__btn_primary{
    color: #fa5864!important;
  }
  .vux-flexbox .vux-flexbox-item:first-child{
    font-size: getRem(28);
  }
  .weui-cell{
    width: 100%;
    padding: getRem(36) 0px getRem(0) 0px!important;
  }
  </style>
  <style scoped>
  .turndown-confirm .weui-dialog__hd{
    padding: 0px!important;
    text-align: center!important;
  }
  .vux-x-textarea.weui-cell{
    padding: 0!important;
  }
  /* textarea.weui-textarea{
    box-sizing: border-box!important;
    padding: 13px!important;
  } */
  .vux-x-textarea /deep/ .weui-textarea{
    box-sizing: border-box!important;
    padding: 13px!important;
  }
  .vux-flex-row{
    align-items: flex-start!important;
  }
  .weui-dialog{
    width: 90%!important;
    max-width: 90%!important;
  }
  .turndown-confirm .weui-dialog{
    width: 90%!important;
    max-width: 90%!important;
  }
  .vux-flexbox .vux-flexbox-item{
    margin-left: 0!important;
  }
  .weui-cell:before{
    left: 0;
    display: none;
  }
</style>
